(function (factory) {
  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root =
    (typeof self == "object" && self.self === self && self) ||
    (typeof global == "object" && global.global === global && global);

  root.nav = factory(
    root,
    root._,
    root.jQuery || root.Zepto || root.ender || root.$
  );
})(function (root, _, $) {
  const addToRoute = function (routes, item) {
    if (item.href.startsWith("#")) {
      var url = item.href.substr(1);
      var target = require.toUrl(item.target);
      routes[url] = target;
    }
  };

  var nav = {
    loadNav: function (loadURL, obj) {
      var that = this;

      obj.on("routeChange", that.setSelectedItem);

      return new Promise(function (resolve, reject) {
        $.getJSON(loadURL, function (navObject) {
          var $navlist = $(".layui-nav");
          var tempItem = _.template($("#tpl-nav-item").html());

          // build nav list
          $navlist.empty();
          _.each(navObject.data, function (item) {
            $navlist.append(tempItem(item));
          });

          // build route
          var routes = {};
          _.each(navObject.data, function (item) {
            addToRoute(routes, item);
            if (item.children) {
              _.each(item.children, function (child) {
                addToRoute(routes, child);
              });
            }
          });
          route.init(routes, obj);
          resolve(navObject);
        });
      });
    },

    setSelectedItem: function (evt, data) {
      console.log("routeChange: " + data);
    },
  };

  return nav;
});
